package com.cr.admin.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.cr.admin.system.mapper.SysDictMapper;
import com.cr.admin.system.mapper.SysDictOptionMapper;
import com.cr.admin.system.pojo.dto.SysDictAddParam;
import com.cr.admin.system.pojo.dto.SysDictQuery;
import com.cr.admin.system.pojo.dto.SysDictUpdateParam;
import com.cr.admin.system.pojo.entity.SysDict;
import com.cr.admin.system.pojo.entity.SysDictOption;
import com.cr.admin.system.service.ISysDictService;
import com.cr.common.exception.ServiceException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Transactional
@Service
public class SysDictServiceImpl implements ISysDictService {

    @Autowired
    private SysDictMapper sysDictMapper;

    @Autowired
    private SysDictOptionMapper sysDictOptionMapper;

    private void checkCodeExists(String code, Long dictId) {
        if (StrUtil.isEmpty(code)) {
            throw new ServiceException("字典代码不能为空");
        }
        LambdaQueryWrapper<SysDict> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(SysDict::getCode, code);
        queryWrapper.ne(dictId != null, SysDict::getId, dictId);
        if (sysDictMapper.selectCount(queryWrapper) > 0) {
            throw new ServiceException("字典代码已存在");
        }
    }

    @Override
    public void insert(SysDictAddParam sysDictAddParam) {
        checkCodeExists(sysDictAddParam.getCode(), null);
        SysDict sysDict = new SysDict();
        BeanUtils.copyProperties(sysDictAddParam, sysDict);
        sysDictMapper.insert(sysDict);
    }

    @Override
    public void deleteByIds(List<Long> ids) {
        if (CollectionUtil.isEmpty(ids)) {
            throw new ServiceException("参数不能为空");
        }
        sysDictMapper.deleteBatchIds(ids);
        // 删除关联的字典项
        sysDictOptionMapper.delete(Wrappers.<SysDictOption>lambdaQuery().in(SysDictOption::getDictId, ids));
    }

    @Override
    public void updateById(SysDictUpdateParam sysDictUpdateParam) {
        checkCodeExists(sysDictUpdateParam.getCode(), sysDictUpdateParam.getId());
        SysDict sysDict = new SysDict();
        BeanUtils.copyProperties(sysDictUpdateParam, sysDict);
        sysDictMapper.updateById(sysDict);
    }

    @Override
    public SysDict selectById(Long id) {
        return sysDictMapper.selectById(id);
    }

    @Override
    public List<SysDict> selectList(SysDictQuery query) {
        return sysDictMapper.selectSysDictList(query);
    }

}
